package com.shuaitao.newsystem.filter;


import com.shuaitao.newsystem.bean.LoginUser;
import com.shuaitao.newsystem.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.AccessDeniedException;
import java.security.Security;
import java.util.Objects;

@Component
@Slf4j
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 获取请求的信息（路径、方法、参数等）
//        String requestURL = request.getRequestURL().toString();
//        // 输出请求信息
//        System.out.println("Request URL: " + requestURL);
//        String authentication = request.getParameter("authentication");
        String authentication = request.getHeader("authentication");
          if (authentication == null) {
            filterChain.doFilter(request,response);
            return;
        }
        String userId;
        try {
            Claims claims = JwtUtil.parseJWT(authentication);
            userId = claims.getSubject();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        // 此处我没有进行判断对比，加设已进行判断对比
//        System.out.println("+++ThreadId"+Thread.currentThread().getId());
//        LoginUser loginUser = AdminServiceImpl.toThreadLocal.get();
        LoginUser loginUser = LoginUser.getInstance();
        if (loginUser.getUser() == null) {
            // 为什么是TOKEN非法，而不是未登录，因为，此时若能运行到这，则证明token是有的，但是是错的
            log.error("用户认证失败，请重新登录！");
            throw new DisabledException("token非法");
        }
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContext context = SecurityContextHolder.getContext();
        context.setAuthentication(usernamePasswordAuthenticationToken);

        filterChain.doFilter(request,response);

    }
}
